<?php
/**
 * 定时任务
 * User: admin
 * Date: 2017/8/17
 * Time: 20:04
 */

namespace Api\Controller;


use Think\Controller;

class BatchController extends  Controller
{

    /**
     * 开奖
     */
    public function lottery()
    {
        $nowtime=date('Y-m-d H:i:s', time());
        print_r("\n");
        print_r("开奖时间：".$nowtime);
        print_r("\n");
        //file_put_contents('./lottery.txt',json_encode($nowtime).PHP_EOL,FILE_APPEND);
        $prize_arr = array(
            '0' => array('id' => 1, 'prize' => '虎', 'v' => 1),
            '1' => array('id' => 2, 'prize' => '狼', 'v' => 5),
            '2' => array('id' => 3, 'prize' => '狗', 'v' => 10),
            '3' => array('id' => 4, 'prize' => '猫', 'v' => 12),
            '4' => array('id' => 5, 'prize' => '鼠', 'v' => 22),
        );
        //开奖规则
        $rule = M('luck_rule')->where('status=1')->find();
        if ($rule['id'] == 1){ //规则一
            //概率档位
            $chance_rule = M('chance_rule')->where('status=1')->find();
            //下注出分统计
            $periods= date('YmdHi', time());
            //$periods = '201804101634';

            $animals = M('animal')->field('id,name,beishu')->where('id != 6')->order('id desc')->select();
            foreach ($animals as $key =>$val){
                $where['periods'] = $periods;
                $where['bet_animal'] = $val['id'];
                $where['is_robot'] =0;
                $total = M('bets')->where($where)->field('sum(money) as total,times')->find();
                $bets = $total['total']*$total['times'];
                $animals[$key]['total_money'] = $bets ? $bets:0;
            }

            array_multisort(array_column($animals,'total_money'),SORT_DESC,$animals);
           /* print_r("出分排序：");
            print_r($animals);
            print_r("\n");*/
            $cnt=0;
            //动物出分排序
            foreach($animals as $key =>$val){
                if($key != count($animals)-1){
                    if ($animals[$key]['total_money'] == $animals[$key + 1]['total_money']) {
                        if ($animals[$key]['beishu'] > $animals[$key + 1]['beishu']){
                            $temp = $animals[$key];
                            $animals[$key] = $animals[$key + 1];
                            $animals[$key + 1] = $temp;
                        }
                    }
                    $cnt += $animals[$key]['total_money'];
                }
            }
            print_r("总下注：");
            print_r($cnt);
            print_r("\n");
            if(!$cnt){
                print_r("总下注2：0");
                //概率填充
                foreach ($prize_arr as $key => $val) {
                    $id = $animals[$key]['id'];
                    $prize_arr[$key]['id'] = $id;
                    $rule_val = "val" . ($key + 1);
                    $gailv =20;
                    $prize_arr[$key]['v'] = $gailv;
                    $prize_arr[$key]['prize'] = $animals[$key]['name'];
                    $arr[$key + 1] = $gailv;
                }
              //  print_r($arr);
            }else {
                print_r("总下注2：1");
                //概率填充
                foreach ($prize_arr as $key => $val) {
                    $id = $animals[$key]['id'];
                    $prize_arr[$key]['id'] = $id;
                    $rule_val = "val" . ($key + 1);
                    $gailv = $chance_rule[$rule_val];
                    $prize_arr[$key]['v'] = $gailv;
                    $prize_arr[$key]['prize'] = $animals[$key]['name'];
                    $arr[$key + 1] = $gailv;
                }
            }
            print_r("概率填充：");
            print_r($arr);
            print_r("\n");
            $rid = $this->get_rand($arr); //根据概率获取奖项id
            $win = $prize_arr[$rid - 1]['prize']; //中奖项
            $win_id = $prize_arr[$rid - 1]['id'];
            //中奖动物记录
            $lot_data['periods'] =$periods;
            $lot_data['bet_animal'] =$win_id;
            $lot_data['uptime'] =time();
            M('lottery_record')->add($lot_data);
            //中奖人记录
            $lot_where['periods'] = $periods;
            $lot_where['bet_animal'] = $win_id;
            $list = M('bets')->where($lot_where)->group('uid')->select();
            $win_uid= array();
            foreach ($list as $key=>$li){
                $u_member = M('ucenter_member')->where('id='.$li['uid'])->find();
                if($u_member['user_type']==3){
                    $is_robot = 1;
                }else{
                    $is_robot = 0;
                }

                $lot_where['uid']=$li['uid'];
                $win=M('bets')->where($lot_where)->field('sum(money) as total,times')->find();
                $total_money = $win['total']*$win['times'];
                $win_data['uid'] = $li['uid'];
                $win_data['periods'] = $periods;
                $win_data['bet_animal'] = $win_id;
                $win_data['total_money'] = $total_money;
                $win_data['is_robot'] = $is_robot;
                $win_data['times'] = $win['times'];
                $win_data['uptime'] = time();
                M('winner_records')->add($win_data);
                //中奖增加元宝

                M('member')->where('uid='.$li['uid'])->setInc('coin',$total_money);
                //中奖，消费记录
                payrecord($li['uid'],$periods,$total_money,3,$li['is_robot']);
                $win_uid[$key]['uid']= $li['uid'];
                $win_uid[$key]['win_money']= $total_money;
            }
            $lottery_record = M('lottery_record')->order('uptime desc')->select();
            $big_winner = M('winner_records')->where('periods='.$periods)->order('total_money desc')->find();
            $big_winner['total_money'] =  $this->format_money($big_winner['total_money']);
            $big_winner['avatar'] = M('member')->where('uid='.$big_winner['uid'])->getField('avatar');
            //排行
            $rank_list=M('winner_records')->order('uptime desc')->group('periods')->limit(10)->select();
            //echo M('winner_records')->getLastSql();
            $ranks = array();
            foreach ($rank_list as $rank){
                $r_list = M('winner_records')->where('periods='.$rank['periods'])->order('total_money desc')->limit(4)->select();
                $ranks = array_merge($ranks,$r_list);
            }
            $rank_lists=array();
            foreach ($ranks as $key=>$val){
                if($key>9){
                    break;
                }else{
                    $rank_lists[]= $val;
                }
            }
            //中奖玩家
            $result_data['win_uid'] = $win_uid;
            //中奖记录
            $result_data['lottery_record'] = $lottery_record;
            //最大赢家
            $result_data['big_winner'] = $big_winner;
            //中奖排行榜记录
            $result_data['rank_list'] = $rank_lists;
            //中奖动物
            $result_data['win_animal'] = $win_id;
            echo "中奖动物id：".$win_id;
          //  response(1,$result_data);

        }else{ //规则二 开龙
            $periods= date('YmdHi', time());
            $win_id=6; //开龙
            //中奖动物记录
            $lot_data['periods'] =$periods;
            $lot_data['bet_animal'] =$win_id;
            $lot_data['uptime'] =time();
            M('lottery_record')->add($lot_data);
            //中奖人记录
            $lot_where['periods'] = $periods;
            $lot_where['bet_animal'] = $win_id;
            $list = M('bets')->where($lot_where)->group('uid')->select();

            $win_uid= array();
            foreach ($list as $key=>$li){
                $lot_where['uid']=$li['uid'];
                $win=M('bets')->where($lot_where)->field('sum(money) as total,times')->find();
                $total_money = $win['total']*$win['times'];
                $win_data['uid'] = $li['uid'];
                $win_data['periods'] = $periods;
                $win_data['bet_animal'] = $win_id;
                $win_data['total_money'] = $total_money;
                $win_data['uptime'] = time();

                //中奖增加元宝
                $u_member = M('ucenter_member')->where('id='.$li['uid'])->find();
                if($u_member['user_type']==3 ){
                    $is_robot = 1;
                }else{
                    $is_robot = 0;
                }
                $win_data['is_robot'] =$is_robot;
                M('winner_records')->add($win_data);

                M('member')->where('uid='.$li['uid'])->setInc('coin',$total_money);
                //中奖，消费记录
                payrecord($li['uid'],$periods,$total_money,3,$li['is_robot']);
                $win_uid[$key]['uid']= $li['uid'];
                $win_uid[$key]['win_money']= $total_money;
            }
            $lottery_record = M('lottery_record')->order('uptime desc')->select();
            $big_winner = M('winner_records')->where('periods='.$periods)->order('total_money desc')->find();
            $big_winner['total_money'] = $this->format_money($big_winner['total_money']);
            $big_winner['avatar'] = M('member')->where('uid='.$big_winner['uid'])->getField('avatar');
            //排行
            $rank_list=M('winner_records')->order('uptime desc')->group('periods')->limit(10)->select();
            //echo M('winner_records')->getLastSql();
            $ranks = array();
            foreach ($rank_list as $rank){
                $r_list = M('winner_records')->where('periods='.$rank['periods'])->order('total_money desc')->limit(4)->select();
                $ranks = array_merge($ranks,$r_list);
            }
            $rank_lists=array();
            foreach ($ranks as $key=>$val){
                if($key>9){
                    break;
                }else{
                    $rank_lists[]= $val;
                }
            }
            //中奖玩家
            $result_data['win_uid'] = $win_uid;
            //中奖记录
            $result_data['lottery_record'] = $lottery_record;
            //最大赢家
            $result_data['big_winner'] = $big_winner;
            //中奖排行榜记录
            $result_data['rank_list'] = $rank_lists;
            //中奖动物
            $result_data['win_animal'] = $win_id;

            //改变抽奖规则，改成规则一
            $map['status']=0;
            $where['id'] = array('not in','3');
            M('luck_rule')->where($where)->save($map);
            $data['status'] = 1;
            $data['uptime'] = time();
            M('luck_rule')->where('id=1')->save($data);
         //   response(1,$result_data);
        }

    }


    /**
     * 自动机器人下注
     */
    public function robotAutoBet(){
        $animals=M('animal')->order('id asc')->select();
        $hour =  date('H', time());
        $periods = date('YmdHi', time()); //期数
       /* if($periods !='201804111549'){
            var_dump($periods);
            exit;
        }*/
        var_dump($periods);
        echo "run";
        $second = date('s', time());
        $result_data['date']= $second;
        $nowtime = date('YmdHi', time());
        $result_data['nowtime']= $nowtime;
        $daycount= array();
        $nightcount = array();
        foreach ($animals as $am){
            $daycount[$am['id']]=$am['day_total'];
            $nightcount[$am['id']]=$am['night_total'];
        }
        //查出机器人
        $map['status'] = 1;
        $map['user_type'] = 3;
        //$members = M('ucenter_member')->where($map)->select();

        if($hour>=10&&$hour<=22){ //白天下注
            //随机每个生肖的总金额
            foreach ($daycount as $key=>$val){
                if($key ==0){$key=1;}
                $count =mt_rand(1,$val);
                if($key !=6){
                    if($count<10){ //小于1万+1万
                        $count= $count+10;
                    }
                }else{
                    if($count<5){ //龙小于5千+5千
                        $count= $count+5;
                    }
                }

                $daycount[$key] = $count;

                //下注，消费记录
                //   payrecord($uid,$periods,$money,2);
            }
            $n=0;
            while(1==1) {
                $members = M('ucenter_member')->where($map)->order(' RAND() LIMIT 10')->select();
            
                $second = date('s', time());
                if ($second >= 50){
                    break;
                }
                if($second > 40){ //下注一半要上榜
                    print_r("下注一半要上榜：");
                    print_r($daycount);
                    if($n<1) {
                        foreach ($daycount as $key => $val){
                            $n++;
                            print_r($key);
                            $count = mt_rand(1, $val);
                            $num = mt_rand(1, 10);
                            $uid = $members[$num]['id'];
                            $data2['periods'] = $periods;
                            $data2['bet_animal'] = $key;
                            $data2['uid'] = $uid;
                            $animal = M('animal')->where('id=' . $key)->find();
                            $data2['times'] = $animal['beishu'];
                            $data2['uptime'] = time();
                            $money = ($count / 2) * 1000 + 3000;
                            $money = substr_replace($money, '0', -3, -2);
                            $data2['money'] = $money;
                            $data2['is_robot'] = 1;
                            $result = M('bets')->add($data2);
                            echo "下注一半额：";
                            print_r($money);
                        }
                    }
                }
                $num=0;
                foreach ($members as $key=>$val){
                    $second = date('s', time());
                    if($second>=50){
                        break;
                    }
                    $member=M('member')->where('uid='.$val['id'])->find();
                    $day_bet_total  = $member['day_bet_total'];
                    $night_bet_total = $member['night_bet_total'];
                    $bet_animal = mt_rand(1,6);
                    $bet_money = mt_rand(1,$day_bet_total);
                    if($bet_money == 1){
                        $bet_money=$bet_money+1;
                    }
                    $money=$bet_money*1000;
                    //是否超过超过下注总量
                    $where['periods'] = $periods;
                    $where['bet_animal'] = $bet_animal;
                    $where['is_robot'] = 1;
                    $total = M('bets')->where($where)->field('sum(money) as total')->find();
                    $total=$total['total']+$money;
                    $animal_total=$daycount[$bet_animal]*1000;
                    /*echo "下注额：";
                    print_r($total);
                    echo "限制总额：";
                    print_r($animal_total);*/
                    print_r("\n");
                    if($total > $animal_total){
                      /*  echo $bet_animal;
                        echo "到达封顶";
                        print_r("\n");*/
                        continue;
                    }

                    //下注龙判断
                    if($bet_animal == 6){
                        /*$where['periods'] = $periods;
                        $where['bet_animal'] = 6;
                        $count = M('bets')->where($where)->count();*/
                        $num++;
                        if($num>2){
                            continue;
                        }
                    }
                   /* echo "自动下注额".$money;
                    echo "时间:".$second;
                    echo "动物id".$bet_animal;
                    print_r("\n");*/
                    $data['periods'] = $periods;
                    $data['bet_animal'] = $bet_animal;
                    $data['uid'] = $val['id'];
                    $animal = M('animal')->where('id=' . $bet_animal)->find();
                    $data['times'] = $animal['beishu'];
                    $data['uptime'] = time();
                    $money =substr_replace($money, '0', -3, -2);
                    $data['money'] = $money;
                    $data['is_robot'] = 1;
                    $result = M('bets')->add($data);
                    //下注，消费记录
                    //payrecord($val['id'],$periods,$money,2);
                }
                sleep(2);

            }

        }else{//晚上下注
            //随机每个生肖的总金额
            foreach ($nightcount as $key=>$val){
                if($key ==0){$key=1;}
                $count =mt_rand(1,$val);
                if($key !=6){
                    if($count<10){ //小于1万+1万
                        $count= $count+10;
                    }
                }else{
                    if($count<5){ //龙小于5千+5千
                        $count= $count+5;
                    }
                }

                $nightcount[$key] = $count;
               /* $num=mt_rand(1,6);
                $uid=$members[$num]['id'];
                $data2['periods'] = $periods;
                $data2['bet_animal'] = $key;
                $data2['uid'] =$uid;
                $animal = M('animal')->where('id=' . $key)->find();
                $data2['times'] = $animal['beishu'];
                $data2['uptime'] = time();
                $money=($count/2)*1000+3000;
                $money =substr_replace($money, '0', -3, -2);
                $data2['money'] = $money;
                $data2['is_robot'] = 1;
                $result = M('bets')->add($data2);*/
                //下注，消费记录
               // payrecord($uid,$periods,$money,2);
            }
            $n=0;
            while(1==1){
                $members = M('ucenter_member')->where($map)->order(' RAND() LIMIT 10')->select();
                $second = date('s', time());
                if($second>=50){
                    break;
                }
                if($second > 40){ //下注一半要上榜
                    print_r("下注一半要上榜：");
                    print_r($daycount);
                    if($n<1) {
                        foreach ($daycount as $key => $val){
                            $n++;
                            print_r($key);
                            $count = mt_rand(1, $val);
                            $num = mt_rand(1, 10);
                            $uid = $members[$num]['id'];
                            $data2['periods'] = $periods;
                            $data2['bet_animal'] = $key;
                            $data2['uid'] = $uid;
                            $animal = M('animal')->where('id=' . $key)->find();
                            $data2['times'] = $animal['beishu'];
                            $data2['uptime'] = time();
                            $money = ($count / 2) * 1000 + 3000;
                            $money = substr_replace($money, '0', -3, -2);
                            $data2['money'] = $money;
                            $data2['is_robot'] = 1;
                            $result = M('bets')->add($data2);
                            echo "下注一半额：";
                            print_r($money);
                        }
                    }
                }
                $num=0;
                foreach ($members as $key=>$val){
                    $second = date('s', time());
                    if($second>=50){
                        break;
                    }
                    $member=M('member')->where('uid='.$val['id'])->find();
                    $day_bet_total  = $member['day_bet_total'];
                    $night_bet_total = $member['night_bet_total'];
                    $bet_animal = mt_rand(1,6);
                    $bet_money = mt_rand(1,$day_bet_total);
                    if($bet_money == 1){
                        $bet_money=$bet_money+1;
                    }
                    $money=$bet_money*1000;
                    //是否超过超过下注总量
                    $where['periods'] = $periods;
                    $where['bet_animal'] = $bet_animal;
                    $where['is_robot'] = 1;
                    $total = M('bets')->where($where)->field('sum(money) as total')->find();
                    $total=$total['total']+$money;
                    $animal_total=$nightcount[$bet_animal]*1000;
                    if($total > $animal_total){
                        continue;
                    }

                    //下注龙判断
                    if($bet_animal == 6){
                        /*$where['periods'] = $periods;
                        $where['bet_animal'] = 6;
                        $count = M('bets')->where($where)->count();*/
                        $num++;
                        if($num>2){
                            continue;
                        }
                    }

                    $data['periods'] = $periods;
                    $data['bet_animal'] = $bet_animal;
                    $data['uid'] = $val['id'];
                    $animal = M('animal')->where('id=' . $bet_animal)->find();
                    $data['times'] = $animal['beishu'];
                    $data['uptime'] = time();
                    $money =substr_replace($money, '0', -3, -2);
                    $data['money'] = $money;
                    $data['is_robot'] = 1;
                    $result = M('bets')->add($data);
                    //下注，消费记录
                    payrecord($val['id'],$periods,$money,2);
                }
                sleep(2);
            }
        }
    }


    /**
     * 清除机器人下注，中奖数据
     */
    public function clear(){
        //清空机器人下注数据
       $map['uptime'] = array('lt', strtotime('-30 minute',time()));
       $res = M('bets')->where($map)->delete();

       //清空一天机器人中奖纪录
        $date=strtotime(date('Y-m-d',time()));
        //$maps['uptime'] = array('lt',$date);
        $maps['uptime'] = array('lt', strtotime('-60 minute',time()));
        $maps['is_robot'] = 1;
        $res2 = M('winner_records')->where($maps)->delete();
        //清空一个小时前的机器人的消费记录
        //$map2['createtime'] = array('lt',$date);
        $map2['createtime'] = array('lt', strtotime('-30 minute',time()));
        $map2['is_robot']  = 1;
        $res3 = M('user_trade')->where($map2)->delete();

        //清空动物中奖纪录
        $map3['uptime'] = array('lt',strtotime('-1 day',time()));
        $res4 = M('lottery_record')->where($map3)->delete();

    }

    /**
     * 统计每天的盈利
     */
    public function statis(){
        $yesterday = strtotime('-1 day',time());
        $date = date('Y-m-d',$yesterday);
        //$date='2018-04-25';
        $map3 = "FROM_UNIXTIME(createtime, '%Y-%m-%d')='" . $date . "'";
        $map4['type'] = 2;
        $map4['is_robot'] = 0;
        $list_cnt=M('user_trade')->field('uid,SUM(money) as totalmoney')->where($map4)->where($map3)->select();
        //echo M('user_trade')->getLastSql();exit;
        $yingli_cnt=0;
        foreach ($list_cnt as $ls){
            $yl_where['type'] = 3;
            $yl_where2 = "FROM_UNIXTIME(createtime, '%Y-%m-%d')='" . $date. "'";
            $yl_where['is_robot'] =0;
            $win=M('user_trade')->where($yl_where)->where($yl_where2)->field('sum(money) as money')->find();
            $win_money= $win['money']?$win['money']:0;
            $yingli_cnt = $ls['totalmoney']-$win['money'];
        }
        if($yingli_cnt<0){
            $yingli_cnt=abs($yingli_cnt);
            $yingli_cnt=$this->format_money2($yingli_cnt);
            $yingli_cnt = "-".$yingli_cnt;
        }else{
            $yingli_cnt=$this->format_money2($yingli_cnt);
        }

        $today_date = date('m-d',$yesterday);
     //   $today_date='04-25';
        $data['date'] =$today_date;
        $data['nums'] =$yingli_cnt;
        $data['uptime'] =date('Y-m-d H:i:s', time());;
        M('statistics')->add($data);

    }

    /*
   * 经典的概率算法，
   * $proArr是一个预先设置的数组，
   * 假设数组为：array(100,200,300，400)，
   * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，
   * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
   * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
   * 这样 筛选到最终，总会有一个数满足要求。
   * 就相当于去一个箱子里摸东西，
   * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
   * 这个算法简单，而且效率非常 高，
   * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
   */
    function get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
    /**
     * 格式化金额
     * @param $money
     */
    function format_money($money){
        if ($money >= 10000) {
            $money = ($money / 10000) . '万';
        } else {
            $money = $money;
        }
        return $money?$money:0;
    }

    /**
     * 格式化金额
     * @param $money
     */
    function format_money2($money){
        if ($money >= 10000) {
            $money = ($money / 10000);
        } else {
            $money = $money;
        }
        return $money?$money:0;
    }
}